package com.hongru.util;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModelProperty;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;

public class BeanChangeUtil {
    public static String contrastObj(Object oldBean, Object newBean) {
        // 创建字符串拼接对象
        StringBuilder str = new StringBuilder();
        // 通过反射获取类的Class对象
        Class clazz = oldBean.getClass();
        // 获取类型及字段属性
        Field[] fields = clazz.getDeclaredFields();
        return jdk8Before(fields, oldBean, newBean, str, clazz);
    }

    public static String jdk8Before(Field[] fields, Object pojo1, Object pojo2, StringBuilder str, Class clazz) {
        int i = 1;
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(ApiModelProperty.class)) {
                    try {
                        Object o1 = field.get(pojo1);
                        Object o2 = field.get(pojo2);
                        /*if (o1 == null || o2 == null) {
                            continue;
                        }*/
                        if (null == o1) {
                            o1 = "";
                        }
                        if (null == o2) {
                            o2 = "";
                        }
                        if (o1.toString().equals(o2.toString())) {
                            continue;
                        }
                        if (o1 instanceof BigDecimal) {
                            if (((BigDecimal) o1).compareTo((BigDecimal) o2) == 0) {
                                continue;
                            }
                        }

                        if (!"".equals(field.getAnnotation(ApiModelProperty.class).name())) {
                            try {
                                String enumJson = field.getAnnotation(ApiModelProperty.class).name();
                                JSONObject enumJsonObj = JSONObject.parseObject(enumJson);
                                o1 = enumJsonObj.getString(o1 + "");
                                o2 = enumJsonObj.getString(o2 + "");
                            } catch (Exception ignored) {

                            }
                        }

                        str.append(i + "." + field.getAnnotation(ApiModelProperty.class).value() + ":" + o1 + "=>" + o2 + "<br>");
                        i++;
                    } catch (Exception e) {

                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str.toString();
    }

}
